import sqlite3
import os
import datetime
import hashlib
import os

DB_PATH = "data/journals.db"
if not os.path.exists("data"):
    os.makedirs("data")

def init_db():
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS journals (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            content TEXT,
            summary TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )
    ''')
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE,
            password_md5 TEXT
        )
    ''')
    conn.commit()
    conn.close()

def add_journal_entry(content, summary, username, type='diary'):
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    now = datetime.datetime.now().isoformat()  # 推荐用 ISO 格式
    cursor.execute(
        "INSERT INTO journals (content, summary, created_at, username, type) VALUES (?, ?, ?, ?, ?)",
        (content, summary, now, username, type)
    )
    conn.commit()
    conn.close()

def get_all_journals():
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("SELECT id, content, summary, created_at, username,type FROM journals")
    rows = cursor.fetchall()
    conn.close()
    return [
        {
            "id": row[0],
            "content": row[1],
            "summary": row[2],
            "created_at": row[3],
            "username": row[4],
            "type": row[5]
        }
        for row in rows
    ]

def delete_journal_entry(journal_id):
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("DELETE FROM journals WHERE id = ?", (journal_id,))
    conn.commit()
    conn.close()

def add_user(username, password_md5):
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("INSERT INTO users (username, password_md5) VALUES (?, ?)", (username, password_md5))
    conn.commit()
    conn.close()

def get_user_by_username(username):
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("SELECT id, username, password_md5 FROM users WHERE username = ?", (username,))
    row = cursor.fetchone()
    conn.close()
    if row:
        return {"id": row[0], "username": row[1], "password_md5": row[2]}
    return None